package com.qf.filter;

import com.qf.encoder.Md5PasswordEncoder;
import com.qf.encoder.NoPasswordEncoder;
import com.qf.encoder.PasswordEncoder;
import com.qf.entity.User;
import com.qf.service.UserDetailsService;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录认证控制
 */
@WebFilter("/login")
public class F001_LoginFilter implements Filter {

    private UserDetailsService userDetailsService = new UserDetailsService();
    private PasswordEncoder passwordEncoder = new NoPasswordEncoder();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取登录的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password"); //明文密码

        //调用UserDetailsService，根据用户名查询用户
        User user = userDetailsService.loadByUsername(username);
        if (user != null){
            //比对密码，将明文密码加密后，和数据库中存储的密码进行比对
            String encod = passwordEncoder.encod(password);
            if (encod.equals(user.getPassword())){
                //登录成功，将用户对象存储到session，放行
                req.getSession().setAttribute("user",user);
                chain.doFilter(req,resp);
            }else{
                //密码错误,回到登录页，告诉用户
                req.setAttribute("errorMsg","密码错误");
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }
        }else{
            //用户名错误,回到登录页，告诉用户
            req.setAttribute("errorMsg","用户名错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }

    @Override
    public void destroy() {

    }
}
